package com.mike.uaa.context;


import com.mike.uaa.core.Authentication;
import com.mike.uaa.core.AuthenticationUtils;
import com.mike.uaa.core.GrantedAuthority;
import com.mike.uaa.core.SimpleGrantedAuthority;
import org.springframework.util.CollectionUtils;
import org.springframework.util.function.SingletonSupplier;

import java.util.Collection;

/**
 * @author z zhang
 */
public interface SecurityContextHolderStrategy {

    /**
     * 清理当前上下文
     */
    void clearContext();

    /**
     * 获取当前上下文
     *
     * @return {@link SecurityContext}
     */
    SecurityContext getContext();


    default DeferredSecurityContext getDeferredContext() {
        return new SupplierDeferredSecurityContext(SingletonSupplier.of(this::getContext), SecurityContextHolder.getContextHolderStrategy());
    }


    void setContext(SecurityContext context);


    default void setDeferredContext(DeferredSecurityContext deferredContext) {
        setContext(deferredContext.get());
    }

    SecurityContext createEmptyContext();

    default boolean isAuthentication() {
        if (getContext() != null) {
            Authentication authentication = getContext().getAuthentication();
            return AuthenticationUtils.isAuthenticated(authentication);
        } else {
            return false;
        }
    }

    default boolean isAuthority(String roleCode) {
        if (isAuthentication()) {
            return false;
        }
        Collection<? extends GrantedAuthority> authorities = getContext().getAuthorities();
        if (CollectionUtils.isEmpty(authorities)) {
            return false;
        }
        SimpleGrantedAuthority simpleGrantedAuthority = SimpleGrantedAuthority.of(roleCode);

        return authorities.stream().anyMatch(
                authority -> authority.equals(simpleGrantedAuthority));
    }
}
